/**
 * 将dom滚动到指定位置
 * @param {HTMLElement} el
 * @param {Number} to
 */
export const scrollTo = (el, to) => {
  let delta = to - el.scrollTop
  let interval = setInterval(() => {
    delta = delta + Math.floor(-delta / 6)
    el.scrollTop = to - delta
    if (Math.abs(delta) <= 6) {
      clearInterval(interval)
    }
  }, 30)
}

/**
 * 计算数组相同值的数量，用于表格的单元格合并
 * @param {Array} data 数组对象
 * @param {String} id 要判断是否可合并的键名
 * @param {String} key 合并单元格数附加在对象上的键名
 */
export const calcSpan = (data, id, key = 'rowspan') => {
  const tempData = []
  const idList = []

  let tempIndex = 0
  for (let i = 0; i < data.length; i++) {
    let isFirst = true
    for (let j = 0; j < idList.length; j++) {
      if (data[i][id] === idList[j]) {
        isFirst = false
        break
      }
    }

    if (isFirst) {
      data[i][key] = 1
      tempIndex = i
      idList.push(data[i][id])
    } else {
      data[tempIndex][key]++
      data[i][key] = 0
    }

    tempData.push(data[i])
  }

  return tempData
}

/**
 * 模拟一条数据
 * @param min
 * @param max
 * @param fixed
 * @returns {*}
 */
export const mockData = (min, max, fixed = 0) => {
  const p = Math.pow(10, fixed)
  return Math.round((Math.random() * max + min) * p) / p
}

export const deleteAfterIndex = (len, index) => {
  return index - (len < 2 && index > 1) ? 1 : 0
}
